<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { classifyFormSchema } from './classify.data'
import { addClassifyDevice } from '@/api/collection/classify/index';
import { useMessage } from '@/hooks/web/useMessage';

const { createMessage } = useMessage();

const props = defineProps({
  searchInfo: { type: [Object, String] as PropType<Record<string, any> | string> },
});

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const rowId = ref('')

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: classifyFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate

  if (unref(isUpdate)) {
    rowId.value = data.record.id
    setFieldsValue({
      ...data.record,
    })
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '添加参数' : '修改参数'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    console.log(props, values);
    if (props.searchInfo.classifyId) {
      // TODO custom api
      const params = { ...values, classifyId: props.searchInfo.classifyId }
      console.log(params)
      await addClassifyDevice(params)
      closeModal()
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
    }
    else {
      createMessage.error(('请选择数据类型'));
    }

  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
